﻿//onload
$(function () {
    if ($("input[title='Title']").length == 0) {
        //Events for DispForm
        JSRequest.EnsureSetup();
        if (JSRequest.QueryString["IsDlg"] != 1) {
            window.location.href = window.location.href.replace(JSRequest.FileName, "View.aspx");
        }
        else {
            $("#onetIDListForm").show();
        }
    }
    else {
        //Events for New/Edit form
        $("#onetIDListForm").show();

        $("#onetIDListForm select[id$=Lookup]").parents("td.ms-formbody").each(function () { //not use for multi lookup field "#onetIDListForm select[id$=SelectCandidate]"

            var fieldWrapper = $(this);

            var text = fieldWrapper.text();
            var regex = /List=([^;]+);Label=([^;]+)(?:;CT=([0-9a-fx]+))?/i;
            var match = regex.exec(text);

            if (match != null) {
                var webUrl = $().SPServices.SPGetCurrentSite(); //ex: http://web.com or http://web.com/SubSite1 or http://web.com/sites/NewSite
                var list = match[1].charAt(0) == "/" ? match[1] : "/" + match[1];
                var label = match[2];
                var ct = match[3];
                var href = webUrl + list + '/NewForm.aspx?Source=' + escape(location.href);
                if (ct != null && ct.length > 0) {
                    href += '&ContentTypeId=' + ct;
                }

                href = "javascript: ShowDialog('" + href + "');return false;"

                var link = '<div style="padding-top: 5px"><img alt="" src="/_layouts/images/rect.gif" style="vertical-align: middle">&nbsp; <a href="#" onclick="' + href + '">' + label + '</a></div>';

                //remove unwrap text
                fieldWrapper.contents().filter(function () {
                    return this.nodeType == 3; //Node.TEXT_NODE
                }).remove();

                fieldWrapper.append(link);
                //fieldWrapper.html(fieldWrapper.html().replace(regex, link));

            }
        });
    }
});

/***** BEGIN Dialog ******/
function Initialize() {
    this.spUiDialogLoaded = true;
}

ExecuteOrDelayUntilScriptLoaded(Initialize, "sp.ui.dialog.js");

function ShowDialog(url) {
    if (SP.ScriptUtility.isNullOrUndefined(spUiDialogLoaded))
        return;
    var dialogOptions = SP.UI.$create_DialogOptions();
    dialogOptions.url = url;
    dialogOptions.dialogReturnValueCallback = Function.createDelegate(this, DialogCloseCallback);
    this.dialog = SP.UI.ModalDialog.showModalDialog(dialogOptions);
}

function DialogCloseCallback(DialogResult, value) {
    if (DialogResult == 1) {
        //SP.UI.ModalDialog.RefreshPage(SP.UI.DialogResult.OK);
        __doPostBack('__Page', 'RefreshPage');
    }
}
/***** END Dialog ******/